package com.example.binjiangapp.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {
    // token密钥
    private static final String SECRECT_STR = "!QWERTYU";

    public static String createToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 30000);

        JWTCreator.Builder builder = JWT.create();

        map.forEach(builder::withClaim);

        return builder
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SECRECT_STR));
    }

    public boolean checkToken(String token) {
        // 创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRECT_STR)).build();

        try {
            jwtVerifier.verify(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static DecodedJWT parseToken(String token) {
        // 创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRECT_STR)).build();

        DecodedJWT verify;
        try {
            verify = jwtVerifier.verify(token);
        } catch (Exception e) {
            return null;
        }
        return verify;
    }

}
